package edu.infomatik.tundra.components;

import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.SessionState;

import edu.infomatik.tundra.logic.security.SystemAccessBean;
import edu.infomatik.tundra.pages.Index;

public class LoginWidget {
	
	@Persist
	private int tries; 
	@InjectPage
	private Index idx;
	
	@SessionState
	private SystemAccessBean user;
	private boolean userExists;
	
	private String userUn="";
	private String userPwd="";
	
	public String getUserUn() {
		return userUn;
	}
	public void setUserUn(String userUn) {
		this.userUn = userUn;
	}
	public String getUserPwd() {
		return userPwd;
	}
	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}
	
	/**
	 * When someone tries unsucessfully to log in more then 5 times he must restart session to try again
	 * @return
	 */
	private boolean isFailedLogin(){
		if (tries>=5) return true;
		return false;
	}
	
	public SystemAccessBean getUser(){
		return user;
	}
	
	@OnEvent(value="submit", component="LoginForm")
	Object onLoginForm(){

		if ( isFailedLogin()) return null;
		user=SystemAccessBean.getInstance(userUn, userPwd);
	    if ( user.getUserName()==null){
	    	user=null;
	    	tries++;
	    	return null;
	    }
	    tries=0;
		return idx.getClass();
		
	}
	public boolean isUserExists() {
		return userExists;
	}
}
